//
//  HTClassMineVC.swift
//  QuitSmokingApp
//
//  Created by   on 2024/3/6.
//

import UIKit
import StoreKit

class HTClassMineVC: HTClassViewController {
    lazy var var_headerImageView: UIImageView = {
        let var_header = UIImageView()
        var_header.layer.cornerRadius = 44.auto()
        var_header.layer.masksToBounds = true
        var_header.contentMode = .scaleAspectFill
        let var_header_image = HTClassImageLocalStorage.ht_getImageFromLocal(var_key: "string_headerImage_data")
        if let var_image = var_header_image {
            var_header.image = var_image
        } else {
            var_header.image = UIImage(named: "icon_header")
        }
        return var_header
    }()
    lazy var var_titleLabel: UIButton = {
        let var_label = UIButton()
        var_label.setTitle("Login", for: .normal)
        var_label.setTitleColor(.white, for: .normal)
        var_label.titleLabel?.font = .systemFont(ofSize: 26, weight: .bold)
        var_label.onTap { [weak self] in
            self?.navigationController?.pushViewController(HTClassPersonalInforVC(), animated: true)
        }
        return var_label
    }()
    lazy var var_tableView: UITableView = {
        let tabelView = UITableView(frame: .zero, style: .plain)
        tabelView.backgroundColor = .clear
        tabelView.delegate = self
        tabelView.dataSource = self
        tabelView.tableFooterView = UIView()
        tabelView.estimatedRowHeight = 0
        tabelView.estimatedSectionFooterHeight = 0
        tabelView.estimatedSectionHeaderHeight = 0
        tabelView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tabelView.sectionHeaderTopPadding = 0
        tabelView.separatorColor = UIColor("#595858")
        return tabelView
    }()
    let var_imagePicker = HTClassImagePickerHelper()
    let var_titles: [String] = ["Theme", "Rate", "Share", "Feedback", "Premium"]
    let var_saveBtn = UIButton()
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: true)
        ht_loginState()
    }
    func ht_loginState() {
        let var_model = HTClassStorage.ht_getPersonalInfor()
        var_saveBtn.isHidden = !HTClassStorage.ht_getLogin()
        var_titleLabel.setTitle(HTClassStorage.ht_getLogin() ? var_model?.var_name ?? "" : "Login", for: .normal)
    }
    override func ht_setUI() {
        super.ht_setUI()
        view.addSubview(var_headerImageView)
        var_headerImageView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(14.auto())
            make.top.equalToSuperview().offset(98.auto())
            make.width.height.equalTo(88.auto())
        }
        let var_header_button = UIButton()
        var_header_button.onTap { [weak self] in
            HTClassPhoneTypeSelectView.showSelectView { type in
                guard let self = self else { return }
                if type == "0" {
                    self.var_imagePicker.ht_presentImagePicker(var_from: self, var_sourceType: .camera, var_completionHandler: { var_image in
                        if var_image != nil {
                            HTClassImageLocalStorage.ht_saveImageToLocal(var_image: var_image!, var_key: "string_headerImage_data")
                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                                let var_hud = HTClassHudView.ht_showLoading()
                                self.var_headerImageView.image = var_image
                                DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                                    var_hud?.hide(animated: true)
                                }
                            }
                        }
                    })
                } else {
                    self.var_imagePicker.ht_presentImagePicker(var_from: self, var_sourceType: .photoLibrary, var_completionHandler: { var_image in
                        if var_image != nil {
                            HTClassImageLocalStorage.ht_saveImageToLocal(var_image: var_image!, var_key: "string_headerImage_data")
                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                                let var_hud = HTClassHudView.ht_showLoading()
                                self.var_headerImageView.image = var_image
                                DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                                    var_hud?.hide(animated: true)
                                }
                            }
                        }
                    })
                }
            }
        }
        view.addSubview(var_header_button)
        var_header_button.snp.makeConstraints { make in
            make.edges.equalTo(var_headerImageView)
        }
        
        
        view.addSubview(var_titleLabel)
        var_titleLabel.snp.makeConstraints { make in
            make.left.equalTo(var_headerImageView.snp.right).offset(20.auto())
            make.centerY.equalTo(var_headerImageView.snp.centerY)
        }
        
        view.addSubview(var_tableView)
        var_tableView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.top.equalToSuperview().offset(210.auto())
            make.height.equalTo(var_titles.count * 70)
        }
        
        
        var_saveBtn.setTitle("Log Out", for: .normal)
        var_saveBtn.setTitleColor(.white, for: .normal)
        var_saveBtn.titleLabel?.font = .systemFont(ofSize: 20, weight: .bold)
        var_saveBtn.layer.cornerRadius = 10
        var_saveBtn.layer.masksToBounds = true
        var_saveBtn.onTap { [weak self] in
            HTClassStorage.ht_savePersonalInfor(HTClassPersonalInforModel())
            HTClassStorage.ht_saveLogin(false)
            self?.ht_loginState()
        }
        self.view.addSubview(var_saveBtn)
        var_saveBtn.snp.makeConstraints { make in
            make.bottom.equalToSuperview().offset(-200)
            make.centerX.equalToSuperview()
            make.width.equalTo(198)
            make.height.equalTo(44)
        }
        var_saveBtn.layoutIfNeeded()
        var_saveBtn.ht_setVerticalGradient(startColor: UIColor("#5CEBFD"), endColor: UIColor("#0691F3"))
       
    }
}

extension HTClassMineVC: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return var_titles.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let var_cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath)
        var_cell.textLabel?.font = .systemFont(ofSize: 14, weight: .medium)
        var_cell.textLabel?.text = var_titles[indexPath.row]
        var_cell.textLabel?.textColor = .white
        var_cell.contentView.backgroundColor = .clear
        var_cell.backgroundColor = .clear
        var_cell.selectionStyle = .none
        return var_cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let var_title = var_titles[indexPath.row]
        switch var_title {
        case "Theme":
            self.navigationController?.pushViewController(HTClassThemeVC(), animated: true)
            break
        case "Rate":
            if let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene {
                SKStoreReviewController.requestReview(in: scene)
            }
            break
        case "Share":
            let var_share_text = "QuitSmoking"
            if let var_url = URL(string: "http://www.baidu.com") {
                let var_activit = UIActivityViewController(activityItems: [var_share_text, var_url], applicationActivities: nil)
                var_activit.excludedActivityTypes = [UIActivity.ActivityType.airDrop]
                var_activit.completionWithItemsHandler = { (activityType, completed, returnedItems, activityError) in
                    // 处理分享完成后的回调逻辑
                    if completed {
                        print("分享成功")
                    } else {
                        print("分享取消")
                    }
                }
                
                if UIDevice.current.model.lowercased() == "ipad" {
                    let var_sourceView = UIApplication.shared.windows[0].rootViewController!.view
                    let var_cell = tableView.cellForRow(at: indexPath)!
                    var var_frame = var_cell.frame
                    var_frame.size.height /= 2
                    var_frame.origin.x = 0
                    var_frame.origin.y = 0
                    var_activit.popoverPresentationController?.sourceView = var_cell
                    var_activit.popoverPresentationController?.sourceRect = var_frame
                    var_activit.popoverPresentationController?.permittedArrowDirections = .up
                }
                
                self.present(var_activit, animated: true, completion: nil)
            }
        case "Feedback":
            self.navigationController?.pushViewController(HTClassFeedbackVC(), animated: true)
        case "Premium":
            self.navigationController?.pushViewController(HTClassPurchaseVC(), animated: true)
        default:
            break
        }
    }
}
